#include <iostream>
#include <signal.h>
#include <functional>
#include "sock.hpp"
#include "Usage.hpp"
#include "util.hpp"

class HttpServer
{
public:
    using func_t = std::function<void(int)>;

private:
    int _listen_sock;
    uint16_t _port;
    Sock _sock;
    func_t _func;

public:
    HttpServer(const uint16_t &port, func_t func) : _port(port), _func(func)
    {
        Sock sock;
        _listen_sock = sock.Socket();
        sock.Bind(_listen_sock, _port);
        sock.Listen(_listen_sock);
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        while (true)
        {
            std::string clientIp;
            uint16_t clientPort = 0;
            int sockfd = _sock.Accpet(_listen_sock, &clientIp, &clientPort);
            if (sockfd < 0)
                continue;

            if (fork() == 0)
            {
                close(_listen_sock);
                _func(sockfd);
                close(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }

    ~HttpServer()
    {
        if (_listen_sock >= 0)
            close(_listen_sock);
    }
};